package com.bml.architect.framework.protocol.dubbo;

import com.bml.architect.framework.Address;
import com.bml.architect.framework.Invocation;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NettyClient {

    private NettyClientHandler nettyClient;

    private ExecutorService executor = Executors.newCachedThreadPool();

    public void start(Address address) {
        EventLoopGroup clientGroup = new NioEventLoopGroup();
        try {
            nettyClient = new NettyClientHandler();
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(clientGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(new StringEncoder());
                            channel.pipeline().addLast(new StringDecoder());
                            channel.pipeline().addLast(nettyClient);
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect(address.getHostname(), address.getPort()).sync();
        } catch (Exception ce) {
            ce.printStackTrace();
        }
    }

    public <T> T send(Address address, Invocation invocation) {
        if (nettyClient == null) {
            start(address);
        }
        nettyClient.setInvocation(invocation);
        try {
            return (T) executor.submit(nettyClient).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


        return null;

    }
}
